package net.gq.logistics.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.gq.logistics.pojo.*;
import net.gq.logistics.service.RoleService;
import net.gq.logistics.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ASUS
 * @date 2020/5/11
 */


@Controller
@RequestMapping("/admin")
public class adminController {


    @Resource(name = "userService")
    private UserService service;

    @Resource(name = "resultData")
    private ResultData resultData;

    @Resource(name = "roleService")
    private RoleService roleService;

    @RequestMapping("/adminPage")
    @RequiresPermissions("admin:adminPage")
    public String adminPage() {

        return "adminPage";
    }

    /** Shiro框架认证失败跳转的页面
     *  1. 如果认证失败，会跳转过来共享错误信息
     *      shiroLoginFailure
     *  2. 如果没有认证强制访问一个页面跳转过来，不会共享错误信息
     * @return
     */
    @RequestMapping("/login")
    public String loginFail(HttpServletRequest request, Model model){
        //获取认证失败的错误信息
        String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
        System.out.println("shiroLoginFailure:"+shiroLoginFailure);
        //org.apache.shiro.authc.IncorrectCredentialsException 凭证异常
        //org.apache.shiro.authc.UnknownAccountException 账号异常

         if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
             //共享错误信息
             model.addAttribute("errorMsg","亲，账号不存在!");
         } else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
             model.addAttribute("errorMsg","亲，密码有误！");
         }


        return "forward:/login.jsp";
    }

    @RequestMapping("/list")
    @RequiresPermissions("admin:list")
    @ResponseBody
    public PageInfo<User> list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, String keyword) {

        System.out.println("keyword:" + keyword);
        UserExample example = new UserExample();
        //开始分页
        PageHelper.startPage(pageNum, pageSize);

        //关键字不为空才做条件查询
        if (StringUtils.isNotBlank(keyword)) {
            //创建限制对象
            UserExample.Criteria criteria = example.createCriteria();

            criteria.andRealnameLike("%" + keyword + "%");

            UserExample.Criteria criteria1 = example.createCriteria();
            criteria1.andUsernameLike("%" + keyword + "%");



            UserExample.Criteria criteria2 = example.createCriteria();
            criteria2.andRolenameLike("%" + keyword + "%");


            example.or(criteria2);
        }


        List<User> users = service.selectByExample(example);

        //创建分页信息对象
        return new PageInfo<User>(users);

    }


    @RequestMapping("/delete")
    @RequiresPermissions("admin:delete")
    @ResponseBody
    public ResultData deleteUser(Long userId) {

        int r = service.deleteByPrimaryKey(userId);

        if (r > 0) {
            //删除成功
            resultData = ResultData.createRs(1, "删除成功！");
        } else {
            resultData = ResultData.createRs(0, "删除失败！");
        }

        return resultData;
    }


    /**
     * @param str
     * @return 批量删除
     */
    @RequestMapping("/deleteAll")
    @RequiresPermissions("admin:delete")
    @ResponseBody
    public ResultData deleteAll(String str) {
        System.out.println("userIds:" + str);
        int result = 0;

        if (StringUtils.isNotBlank(str)) {
            String[] index = str.split(",");
            for (String c : index) {
                //删除数据
                result = service.deleteByPrimaryKey(Long.valueOf(c));

            }
        }

        if (result > 0) {
            resultData = ResultData.createRs(1, "删除数据成功！");
        } else {
            resultData = ResultData.createRs(0, "删除数据失败");
        }


        return resultData;


    }


    /**
     * @param
     * @return 编辑，新增，修改页面
     */
    @RequestMapping("/edit")

    public String edit(Model model, Long userId) {

        //修改操作
        if (userId != null) {
            //编辑操作

            User user = service.selectByPrimaryKey(userId);

            model.addAttribute("user", user);

        }


        //查询出所有的角色，以供新增修改管理员分配角色信息
        RoleExample exampl = new RoleExample();

        List<Role> roles = roleService.selectByExample(exampl);

        model.addAttribute("roles", roles);

        return "adminEdit";
    }

    /**
     * 检查用户名是否存在
     *
     * @param username
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public boolean query(String username) {
        System.out.println(username);

        UserExample example = new UserExample();

        //创建条件语句
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);

        List<User> users = service.selectByExample(example);

        return users.size() == 0 ? true : false;
    }

    /**
     * 新增用户
     *
     * @return
     */
    @RequestMapping("/insert")
    @RequiresPermissions("admin:insert")
    @ResponseBody
    public ResultData insert(User user) {

        //设置当前创建日期
        user.setCreateDate(new Date());


        //设置盐
        String salt = UUID.randomUUID().toString().substring(0, 5);
        user.setSalt(salt);

        //设置加密后的密码
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
        user.setPassword(md5Hash.toString());


        int result = service.insert(user);

        if (result > 0) {
            resultData = ResultData.createRs(result, "添加成功!");
        } else {
            resultData = ResultData.createRs(result, "添加失败！");
        }

        return resultData;


    }


    /** 修改管理员数据
     * @param user
     * @return
     */
    @RequestMapping("/update")
    @RequiresPermissions("admin:update")
    @ResponseBody
    public ResultData update(User user) {

        System.out.println(user);

        //加盐
        String salt = UUID.randomUUID().toString().substring(0, 5);
        user.setSalt(salt);

        //设置加密后的密码
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
        user.setPassword(md5Hash.toString());

        int result = service.updateByPrimaryKeySelective(user);

        if (result > 0) {
            resultData=ResultData.createRs(result,"更新成功");
        }else {
            resultData=ResultData.createRs(result,"更新失败");
        }

        return resultData;
    }





}
